package com.sinog.front.config.xss;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @desc 自定义cors过滤器
 * @author lzq
 * @date 2021-07-26 12:27
 */
@Component
@Slf4j
public class SimpleCorsFilter implements Filter {

    @Value("${gkzx.azbj.auth.auth-server-url}")
    private String localServerUrl;
    @Value("${gkzx.azbj.auth.auth-server-url-diy}")
    private String localServerUrlDiy;

    /**
     * XSS过滤器
     * @param req req
     * @param res res
     * @param chain chain
     */
    @Override
    public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException, ServletException {
        XssHttpServletRequestWrapper request = new XssHttpServletRequestWrapper((HttpServletRequest)req);
        HttpServletResponse response = (HttpServletResponse)res;
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, token");
        response.addHeader("X-Content-Type-Options","nosniff");
        response.setHeader("Strict-Transport-Security","max-age=31536000");
        response.addHeader("Referer-Policy","origin");
        response.addHeader("X-Permitted-Cross-Domain-Policies","master-only");
        response.addHeader("X-Download-Options","noopen");
        response.addHeader("X-Frame-Options","SAMEORIGIN");
        String serverName = request.getServerName();
        if(!StringUtils.isBlank(serverName)) {
            //针对天津做一个单独的放开，暂定
            if(checkBlankList(serverName)||"10.152.19.17".equals(serverName)) {
                log.info("进入系统的ip:{}",serverName);
                chain.doFilter(request,response);
            } else {
                log.error("未进入系统的ip:{}",serverName);
                response.setStatus(403);
                response.flushBuffer();
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

    /**
     * 判断主机是否存在白名单中
     * @param host host
     * @return boolean
     */
    private boolean checkBlankList(String host) {
        //这里host有时候会包括项目端口号，下面白名单IP可以写成一个集合，看集合是否包含当前访问IP
        return localServerUrl.contains(host) || localServerUrlDiy.contains(host);
    }
}